<!DOCTYPE html>
<html>
<script src="utils/api.js"></script>
<script src="utils/re.js"></script>
<script src="utils/cache.js"></script>
<script>

/**
 * Copyright 2009 Daniel Pupius (http://code.google.com/p/fittr/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *
 * Background Page.
 * Used for API access from the content scripts.
 */

var API_KEY = '92f14cd6624fc2f44d1f59f119ece00a';

chrome.extension.onConnect.addListener(onPortConnect);

var dataCache = new Cache;

function onPortConnect(port) {
  var type = port.name.split('_')[0];
  var listener = function(params, port) {
    if (type == 'setPref') {
      localStorage[params.name] = params.value;
      port.postMessage(params.value);
    
    } else if (type == 'getPref') {
      port.postMessage(localStorage[params.name]);
    
    } else {
      var cachedValue;
      if (!params.force) 
        cachedValue = dataCache.get(type, params);
      if (cachedValue) {
        console.log('Data available in local cache ' + type);
        port.postMessage(cachedValue);
      } else {
        makeRequest(port, type, params);
      }
    }
    port.onMessage.removeListener(listener);
  };  
  port.onMessage.addListener(listener);
}

function makeRequest(port, type, params) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      var status = xhr.status;
      var response, err = '';
      try {
        response = JSON.parse(xhr.responseText);
      } catch (e) {
        status = -1;
        err = e.message;
      }
      var responseObject = {
        status: status,
        content: response,
        error: err
      };
      if (status == 200 && !params.nocache) dataCache.put(type, params, responseObject);
      port.postMessage(responseObject);
    }
  };
  var url = 'http://api.flickr.com/services/rest/?' +
      'format=json&' +
      'nojsoncallback=1&' + 
      'method=' + type + '&' +
      'api_key=' + api.API_KEY;
  for (var key in params) {
    url += '&' + key + '=' + params[key];
  }
  xhr.open('GET', url);
  xhr.send();
}



// Listen for tab changes and enable the page action if appropriate.
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo) {
  checkTabForFlickrImg(tabId);
});

chrome.tabs.onCreated.addListener(function(tab) {
  checkTabForFlickrImg(tab.id);
});

function checkTabForFlickrImg(tab) {
  chrome.tabs.get(tab, function(info) {
    var url = info.url;
    if (url && re.PHOTO_URL.test(url)) {
      console.log('Found flickr Img URL: ' + url);
      chrome.pageAction.show(tab);
    }
  });
}

chrome.pageAction.onClicked.addListener(function(tab) {
  var m = re.PHOTO_URL.exec(tab.url);
  if (m) {
    chrome.tabs.update(tab.id,
        {url: 'http://www.flickr.com/photo.gne?id=' + m[1]});
  }
});

</script>
</html>